package serial

import (
	"gitee.com/injoyai/goutil/oss/io"
	"github.com/goburrow/serial"
)

type (
	Config      = serial.Config
	RS485Config = serial.RS485Config
	Parity      string
)

func (this Parity) String() string {
	switch this {
	case ParityNone:
		return "无校验"
	case ParityOdd:
		return "奇校验"
	case ParityEven:
		return "偶校验"
	default:
		return "未知"
	}
}

const (
	ParityNone Parity = "N" //无校验
	ParityOdd  Parity = "O" //奇校验
	ParityEven Parity = "E" //偶校验
)

type Client struct {
	*io.Client
}

func New(cfg *Config) (*Client, error) {
	p, err := serial.Open(cfg)
	if err != nil {
		return nil, dealErr(err, cfg.Address)
	}
	c := io.NewClient(p)
	c.SetKey(cfg.Address)
	return &Client{c}, nil
}

/*

type Client struct {
	option    *Option
	mu        sync.Mutex
	client    io.ReadWriteCloser
	debug     bool
	timeout   time.Duration
	closeSign chan *struct{}
	closeErr  error
}

func (this *Client) Read() ([]byte, error) {
	buffer := make([]byte, 512)
	n, err := this.client.Read(buffer)
	if err != nil {
		return nil, err
	}
	return buffer[:n], nil
}

func (this *Client) SetTimeout(timeout time.Duration) {
	this.timeout = timeout
}

func (this *Client) Debug(b ...bool) {
	this.debug = !(len(b) > 0 && !b[0])
}

func (this *Client) Closed() bool {
	select {
	case <-this.closeSign:
		return true
	default:
		return false
	}
}

func (this *Client) Close() error {
	select {
	case <-this.closeSign:
		return nil
	default:
		this.closeErr = errors.New("已关闭")
		return this.client.Close()
	}
}

func (this *Client) Send(request []byte) (response []byte, err error) {
	defer func() {
		err = dealErr(err, this.option.Address)
		if this.debug {
			log.Println("[串口]", hex.EncodeToString(request), ">>>", hex.EncodeToString(response))
		}
	}()
	this.mu.Lock()
	defer this.mu.Unlock()
	err = this.connect()
	if err != nil {
		return
	}
	_, err = this.client.Write(request)
	if err != nil {
		return
	}
	<-time.After(time.Millisecond * 100)
	buff := make([]byte, 512)
	length, err := this.client.Read(buff)
	if err != nil {
		return nil, err
	}
	response = buff[:length]
	return
}

func (this *Client) connect() (err error) {
	select {
	case <-this.closeSign:
		return this.closeErr
	default:
	}
	if this.client == nil {
		this.client, err = serial.Open(this.option)
	}
	return
}


*/
